package com.cswnode.demo.controller;

import com.cswnode.demo.entity.Page;
import com.cswnode.demo.entity.Post;
import com.cswnode.demo.service.EnterpriseService;
import com.cswnode.demo.service.PostService;
import com.cswnode.demo.util.ResponseVo;
import com.cswnode.demo.vo.PostVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author csw
 * @create 2021/3/14 19:38
 */
@Api(tags = "岗位管理")
@RequestMapping("/post")
@RestController
public class PostController {
    @Autowired
    private PostService postService;
    @Autowired
    private EnterpriseService enterpriseService;

    @ApiOperation(value = "添加岗位")
    @PostMapping("/add")
    public ResponseVo add(@RequestBody Post post){
        if (post == null){
            return ResponseVo.error("专业类型不能为空！");
        }
        Post insert = postService.insert(post);
        if (insert == null){
            return ResponseVo.error("添加失败！");
        }
        return ResponseVo.success("添加成功！");
    }

    @ApiOperation(value = "获得所有岗位")
    @GetMapping("/query")
    public ResponseVo query(@RequestParam(defaultValue = "1") Integer current,
                            @RequestParam(defaultValue = "10")Integer limit,
                            String postName, String entName)
    {
        List <Long> entIds = null;
        if (StringUtils.isNotEmpty(entName)){
            entIds = enterpriseService.queryEntIdByName(entName);
        }
        Map<String,Object> result = new HashMap<>();
        Page page = new Page();
        page.setCurrent(current);
        page.setLimit(limit);
        page.setRows(postService.selectNum(postName,entIds));
        List<PostVo> postVos = postService.queryAllVo(page.getOffset(), page.getLimit(), postName, entIds);
        result.put("page",page);
        result.put("postVos",postVos);
        return ResponseVo.success(result);
    }

    @ApiOperation(value = "修改岗位")
    @PostMapping("/update")
    public ResponseVo update(@RequestBody Post post){
        if (post == null || post.getPostId() == null){
            return ResponseVo.error("修改失败");
        }
        Post update = postService.update(post);
        return ResponseVo.success("修改成功");
    }

    @ApiOperation(value = "删除岗位")
    @GetMapping("/delete/{postId}")
    public ResponseVo delete (@PathVariable("postId")Long postId){
        if (postId == null){
            return ResponseVo.error("删除失败！");
        }
        boolean result = postService.deleteById(postId);
        if (!result){
            return ResponseVo.error("删除失败");
        }
        return ResponseVo.success("删除成功");
    }
}
